import re
import json
from datetime import datetime
import jenkins

def get_min(tm):
    t1 = tm.split()
    t0 = 0
    while t1:
        if t1[1] == "hr":
            t0 += float(t1[0]) * 60
            t1.pop(0)
            t1.pop(0)
        elif t1[1] == "min":
            t0 += float(t1[0])
            t1.pop(0)
            t1.pop(0)
        elif t1[1] == "sec":
            t0 += float(t1[0]) / 60
            t1.pop(0)
            t1.pop(0)
        elif t1[1] == "ms":
            t1.pop(0)
            t1.pop(0)
        else:
            break
    return t0



# URL = "http://192.168.171.129:8080/jenkins"
# USERNAME = "johnny"
# TOKEN = "118ceaea6aa55bc83b8638065f0a709ed1"

URL = "http://jenkins.senseauto.com/"
USERNAME = "liuwei8"
TOKEN = "1110580c7dfe0c4f604afd9aec72716c5b"

server = jenkins.Jenkins(URL, username=USERNAME, password=TOKEN)

# 获取所有view view-pattern 键值对
# views = server.get_views()
# vname_vpat = dict()
# for v_name in [view["name"] for view in views]:
#     config = server.get_view_config(v_name)
#     pattern = re.findall(r"<name>(.*?)</name", config)
#     if pattern:
#         vname_vpat[v_name] = pattern[0]
# print(vname_vpat)

# 获取每个所有job（流水线）
jobs_info = server.get_all_jobs()
jobs = [item.get("fullname", None) for item in jobs_info]


# 获取每个view下的每个job的config, 并提取出 execCommand
# print("{:<30}|{:<30}|{:<30}".format("pipeline_name", "branch_name", "jenkinsfile_path"))
# dic = dict()
# for idx, job in enumerate(jobs, 1):
#     config = server.get_job_config(job)
#     branch_name = re.findall("<name>\*/(.*?)</name>", config)
#     if not branch_name:
#         break
#     branch_name = branch_name[0]
#     if branch_name in dic.keys():
#         dic[branch_name][0] += 1
#         dic[branch_name][1].append(job)
#     else:
#          dic[branch_name] = [1, [job]]
# for branch, pipeline_times in sorted(dic.items(), key=lambda x: x[1][1], reverse=True):
#     print("{:<40}: {}".format(branch, pipeline_times))
    # jenkins_file_path = re.findall("<scriptPath>(.*?)</scriptPath>", config)
    # print("{:<30}|{:<30}|{:<30}".format(job, branch_name[0], jenkins_file_path[0]))

job_bnum = dict()
for idx, job in enumerate(jobs, 1):
    job_bnum[job] = server.get_job_all_build(job)
for job, build_lst in job_bnum.items():
    for num in build_lst:
        run_wait_time = server.get_build_time(job, num)
        if not run_wait_time:
            continue
        tm = server.get_build_info(job, num)["timestamp"]
        tmf = datetime.fromtimestamp(tm/1000)
        print("{}, {}, {}, {}".format(job, tmf, get_min(run_wait_time["run_time"]), get_min(run_wait_time["wait_time"])))

            
        